package com.example.demo.controller;

import com.example.demo.model.Calc;
import com.example.demo.service.CalcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class CalcController {
    @Autowired
    private CalcService calcService;

    @RequestMapping("/save")
    public int save(Calc calc){
        calculate(calc);
        int ret = calcService.save(calc);
        if(ret==1){
            log.info("保存成功！");
            return calc.getResult();
        }else {
            log.info("保存失败！");
            return -1;
        }
    }

    @RequestMapping("/load")
    public List<Calc> load(){
        List<Calc> calcList=calcService.load();
        return calcList;
    }

    public void calculate(Calc calc){
        switch (calc.getStr()){
            case "+":
                calc.setResult(calc.getNum1()+calc.getNum2());

                break;
            case "-":
                calc.setResult(calc.getNum1()-calc.getNum2());
                break;
            case "*":
                calc.setResult(calc.getNum1()*calc.getNum2());
                break;
            case "/":
                if(calc.getNum2()!=0){
                    calc.setResult(calc.getNum1()/calc.getNum2());
                    break;
                }
        }
    }
}
